<template>
  <div class="页面容器">
    <header class="头部">
      <div class="tit">家教任务兼职</div>
      <div class="menu">
        <i class="iconfont icon-fabusekuai" style="font-size: 22px;margin-left: 10px;" @click="go_page('/issue')"></i>
        <div class="search-txt">
          <input type="search" ref="search">
          <i class="iconfont icon-sousuo-F" style="font-size: 22px;margin-left: 10px;" @click="searchOrder"></i>
        </div>
        <i class="iconfont icon-shaixuan" style="margin-right: 10px;" @click="flesh_Order()"></i>
      </div>
    </header>
    <main class="主要内容区域">
      <div class="任务项" v-for="(item, index) in orders">
        <div class="top">
          <div class="left" @click="showUser(item.parent, item.id)">
            <div class="sub">{{ item.subject }}</div>
            <span><strong>起始时间：</strong> {{ item.startDate }}</span>
            <span><strong>截止时间：</strong> {{ item.endDate }}</span>
            <span><strong>薪&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;资：</strong> {{ item.salary }}</span>
            <span><strong>年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级：</strong> {{ item.grade }}</span>
          </div>
          <div class="right">
            <img @click="showUser(item.parent, item.id)" :src="`${this.BASE_URL}/file/getPortrait/${item.parent}`"
              alt="">
            <div v-if="item.parent != user.username" @click="application(index)">申请兼职</div>
            <div style="background-color: #9c9393;" v-else @click="applicationMe(index)">我的兼职</div>
          </div>
        </div>
        <div class="bot" @click="showUser(item.parent, item.id)">
          <div class="item">
            <span><strong>要&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;求：</strong> {{ item.demand }}</span>
            <span><strong>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;点：</strong> {{
              item.shen + item.shi + item.xian + item.street }}</span>
          </div>
        </div>
      </div>
    </main>
    <div class="search" v-show="isShowSearch === 1" @click="noshowsearch">
      <div></div>
    </div>
    <!-- 申请表单弹窗 -->
  </div>
</template>

<script>
import {
  isPermissionGranted,
  requestPermission,
  sendNotification,
} from '@tauri-apps/plugin-notification';
import emitter from '../../bus';
import axios from 'axios';
import settings from '../../settings.json'
import { show } from '@tauri-apps/api/app';
import { setStatusBarColor } from 'tauri-plugin-status-bar-color-api';
export default {
  data() {
    return {
      isShowUser: 0,
      BASE_URL: '',
      isShowSearch: 0,
      任务列表: [
        {
          id: 1,
          标题: "数学家教",
          学科: "数学",
          地点: "线上",
          薪资: "每小时20美元",
          要求: "具备良好的代数和几何知识"
        },
        {
          id: 2,
          标题: "英语家教",
          学科: "英语",
          地点: "线下，市中心",
          薪资: "每小时18美元",
          要求: "母语为英语或英语流利"
        },
        // 可以在这里继续添加更多的家教兼职任务对象
      ],
      申请弹窗可见: false,
      申请表单数据: {
        姓名: '',
        联系方式: '',
        个人简介: ''
      },
      orders: [],
      user: null,
      address: null,
    };
  },
  created() {
    setStatusBarColor("#ffffff")
    this.BASE_URL = settings.ipAddress

    this.user = JSON.parse(localStorage.getItem("currentUser"))
    this.address = JSON.parse(localStorage.getItem("currentAddress"))
    this.getValidAppointments()


    emitter.on('showMine', (e) => {
      this.isShowUser = 0
    })
  },
  mounted() {
    // 处理搜索框的回车事件
    this.$refs.search.addEventListener('keydown', async (e) => {
      if (e.key === 'Enter') {
        let searchValue = this.$refs.search.value;
        axios.get(this.BASE_URL + '/order/searchOrders', {
          params: {
            keyword: searchValue
          }
        }).then(res => {
          this.orders = res.data
        }).catch(error => {
          console.error('Error searching orders:', error);
        })

        // this.isShowSearch = 0;
        // let permissionGranted = await isPermissionGranted();

        // // 如果没有，我们需要请求它
        // if (!permissionGranted) {
        //   const permission = await requestPermission();
        //   permissionGranted = permission === 'granted';
        // }

        // // 一旦获得许可，我们就可以发送通知
        // if (permissionGranted) {
        //   sendNotification({ title: '申请已经成功', body: 'Tauri is awesome!' });
        // }
      }
    })
  },
  methods: {
    playAudio() {
      emitter.emit('playAudio', 'audio.mp3');
    },
    showUser(name, oid) {
      this.isShowUser = 1
      this.$router.push({ path: '/issueDetail', query: { username: name, id: oid } })
    },
    showSearch() {
      this.isShowSearch = 1;
    },
    noshowsearch() {
      this.isShowSearch = 0;
    },
    async application(index) {
      const applay = {
        parent: this.orders[index].parent,
        tutor: this.user.username,
        oid: this.orders[index].id,
        startDate: this.orders[index].startDate,
        endDate: this.orders[index].endDate,
        salary: this.orders[index].salary,
        grade: this.orders[index].grade,
        subject: this.orders[index].subject,
        shen: this.orders[index].shen,
        shi: this.orders[index].shi,
        xian: this.orders[index].xian,
        street: this.orders[index].street,
        demand: this.orders[index].demand
      };
      axios.post(this.BASE_URL + '/applay/insert', applay).then(res => {
        if (res.data == 0) {
          alert("已申请该兼职，请等待对方回复")
        } else {
          alert("申请成功，请等待对方回复")
        }
      }).catch(error => {
        alert("任务无法申请")
        console.error('Error inserting applay:', error);
      })
    },
    applicationMe(index) {
      alert("无法申请我的兼职任务")
    },
    async getValidAppointments() {
      let time = new Date();

      axios.get(`${this.BASE_URL}/order/validAppointments`, {
        params: {
          startDate: time.toLocaleString(),
          username: this.user.username,
          shi: this.address.shi,
        }
      }).then(res => {
        console.log('有效预约查询结果:', res.data);
        this.orders = res.data
        // this.$store.commit("setFriends", res.data)
      }).catch(error => {
        console.log('查询有效预约时出错:', error);
      })
      // try {
      //   const response = await axios.get(`${this.BASE_URL}/order/validAppointments`, {
      //     endDate: time.toISOString()
      //   });

      // } catch (error) {

      // }
    },
    go_page(r) {
      this.isShowUser = 1
      this.$router.push(r)
    },
    flesh_Order() {
      // alert("刷新")
      this.getValidAppointments()
    },
    searchOrder() {
      let searchValue = this.$refs.search.value;
      axios.get(this.BASE_URL + '/order/searchOrders', {
        params: {
          keyword: searchValue
        }
      }).then(res => {
        this.orders = res.data
      }).catch(error => {
        console.error('Error searching orders:', error);
      })
    }
  }
};
</script>

<style lang="scss" scoped>
// 定义颜色变量，方便统一管理和修改颜色
$背景颜色: #e3f0e1;
$头部背景颜色: #ffffff;
$任务项背景颜色: white;
$任务项阴影颜色: rgba(0, 0, 0, 0.1);
$任务标题颜色: #4caf50;

// 整体页面容器样式
.页面容器::-webkit-scrollbar {
  display: none;
}

.页面容器 {
  position: absolute;
  width: 100vw;
  height: calc(100vh - 60px);
  font-family: Arial, sans-serif;
  background-color: $背景颜色;
  margin: 0;
  padding: 0;
  overflow: auto;
  scrollbar-width: none;

  /* 仅适用于 WebKit 浏览器 */
  ::-webkit-scrollbar {
    display: none;
  }

  // 标题栏样式
  .头部 {
    position: absolute;
    width: 100vw;
    background-color: $头部背景颜色;

    height: 70px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #d3d3d3;

    .tit {
      height: 30px;
      width: 100vw;
      text-align: center;
      line-height: 30px;
      font-size: 22px;
      font-weight: 500;
      color: #000;
      // background-color: #00ff0d;
    }

    .menu {
      height: 39px;
      width: 100vw;
      line-height: 39px;
      display: flex;
      justify-content: space-around;

      // background-color: #ea0606;

      .search-txt {
        display: flex;
        justify-content: space-around;
        align-items: center;

        input {
          width: 50vw;
          height: 22px;
          font-size: 12px;
          background-color: #dbdbdb;
          outline: none;
          border-radius: 14px;
          border: 0.11px solid #0c9020;
        }

        // background-color: #5d00ff;
        // height: 37px;
        width: 62vw;
        // border: 1px solid #0c9020;
      }
    }

    img {
      width: 26px;
      height: 26px;
      position: fixed;
      right: 10vw;
      top: 30px;
    }
  }

  // 主要内容区域样式
  .主要内容区域::-webkit-scrollbar {
    display: none;
  }

  .主要内容区域 {
    overflow: auto;
    scrollbar-width: none;
    margin-top: 70px;

    height: calc(100vh - 130px);
    /* 仅适用于 WebKit 浏览器 */

    width: 100vw;
    display: flex;
    flex-direction: column;
    align-items: center;

    // 每个任务项样式
    .任务项 {
      display: flex;
      flex-direction: column;
      background-color: $任务项背景颜色;
      border-radius: 5px;
      box-shadow: 0 2px 5px $任务项阴影颜色;
      margin-top: 10px;
      margin-bottom: 10px;
      width: 90vw;
      height: fit-content;

      span {
        margin-top: 2px;
        margin-bottom: 0px;
        // background-color: #f40e0e;
        height: fit-content;
        line-height: 22px;
        font-size: 13px;
        overflow-wrap: break-word;

        white-space: normal;
        /* 默认值，允许换行 */
        word-wrap: break-word;
        overflow-wrap: break-word;
      }

      .sub {
        // background-color: #ff0303;
        margin-top: 4px;
        color: $任务标题颜色;
      }

      .bot {
        height: fit-content;
        width: 90vw;
        margin-top: 0;

        margin-left: 0px;


        .item {
          margin-bottom: 10px;
          margin-top: 0px;
          margin-left: 10px;
          display: flex;
          flex-direction: column;
          max-width: 84vw;

          span {
            border-bottom: 0.1px solid #000;
          }
        }

        p {
          width: 80vw;
          height: fit-content;
          overflow-wrap: break-word;

          white-space: normal;
          /* 默认值，允许换行 */
          word-wrap: break-word;
          overflow-wrap: break-word;
          /* 允许长单词或 URL 换行 */
          /* 允许长单词或 URL 换行 */
        }
      }

      .top {
        height: fit-content;
        width: 90vw;
        display: flex;
        justify-content: start;

        .left {

          width: 58vw;
          margin-left: 10px;
          display: flex;
          flex-direction: column;

          p {

            width: 50vw;
            max-width: 50vw;
            height: fit-content;
            overflow-wrap: break-word;

          }

          span {
            border-bottom: 0.1px solid #000;
          }
        }

        .right {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin-top: 10px;
          margin-left: 27px;
          align-items: center;
          height: 90%;
          // background-color: #f10707;


          img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
          }

          div {

            width: 70px;
            height: 24px;
            font-size: 10px;
            text-align: center;
            margin-top: 4px;
            line-height: 24px;
            border-radius: 4px;
            color: white;
            background-color: #0c9020;
          }
        }


      }
    }
  }

  .search {
    height: 60vh;
    width: 90vw;
    background: #ed0a0a;
    position: fixed;
    left: 5vw;
    top: 17vh;

    div {
      width: 70vw;
      background: #000;
      height: 50vh;
    }
  }
}
</style>
